/**
 * Description：工人实测值录入 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.9.5
 */
const { reactive, ref } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useInputCheckResult() {
  const baseAPI = '../../../Ashx/InputCheckPointResultVue3PageHandler.ashx';

  const inputCheckResultDialogChildContainerRef = ref(null);//子序号批次表格ref
  const inputCheckResultDialogCheckItemTableRef = ref(null);//检测项表格ref
  const inputCheckResultDialogCheckResultTableRef = ref(null);//检测项结果表格ref
  const importCheckResultUploadRef = ref(null);//检查项导入ref
  const fileUploadRef = ref(null);//文件上传ref

  let inputCheckResultObj = reactive({
    dialogVisible: false,
    tabObj: {
      container: 'container',
      checkitem: 'checkitem',
      childcontainer: 'childcontainer',
      checkresult: 'checkresult',
      inputZone: 'inputZone',
      importCheckPoint: 'importCheckPoint',
      uploadZone: 'uploadZone',
    },
    upload: { type: '公开' },
    containerList: [],//批次信息表格
    checkitemList: [],//检测项表格
    childContainerList: [],//子批次表格
    checkItemResultList: [],//已录入结果表格
    checkResultImportfileList: [],//检测项导入的文件
    fileUploadList: [],//上传的文件
    // 文件上传额外附加的参数
    fileUploadParams: { uploadType: '1', checkPointResult: [] },
    action: "../../../Ashx/InputCheckPointResultVue3PageHandler.ashx?actions=importWorkerCheckPointItem"//检测项导入后端路径
  });
  let currentUserInfo = {};// 当前登录用户信息

  // 初始化对话框数据
  async function initInputCheckResultDialogData(selectionRow, userInfo) {
    inputCheckResultObj.dialogVisible = true;
    resetDialogData();//先重置数据
    currentUserInfo = userInfo.value;
    inputCheckResultObj.containerList = [selectionRow];//给【流水卡信息】表格赋值
    const { containerid, workflowstepid, containertype } = selectionRow;
    if (containertype === 3) {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=getChildContainerList`,
        data: { type: 'getChildContainerList', containerid }
      });
      inputCheckResultObj.childContainerList = data.value;//子批次表格
      inputCheckResultDialogChildContainerRef.value.toggleAllSelection();//子批次表格默认全选
    }
    await getCheckItemList({ containerid, workflowstepid, stepinfoid: '' });
  }

  // 重置数据
  function resetDialogData() {
    inputCheckResultObj.containerList = [];
    inputCheckResultObj.checkitemList = [];
    inputCheckResultObj.childContainerList = [];
    inputCheckResultObj.checkItemResultList = [];
    inputCheckResultObj.checkResultImportfileList = [];
    inputCheckResultObj.fileUploadList = [];
  }

  // 查询检测项
  async function getCheckItemList({ containerid, workflowstepid, stepinfoid }) {
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getCheckItemList`,
      data: {
        type: 'getCheckItemList',
        containerID: containerid,
        workFlowStepId: workflowstepid,
        containerStepWorkReportID: "",
        stepInfoID: stepinfoid,
      }
    });
    for (const i of data.value) {
      i.containerid = containerid;//缓存批次id
      i.workflowstepid = workflowstepid;//缓存工序id
    }
    inputCheckResultObj.checkitemList = data.value;
  }

  // 检测项表格row点击事件
  function checkItemRowClick(row, column, event) {
    inputCheckResultDialogCheckItemTableRef.value.clearSelection();
    inputCheckResultDialogCheckItemTableRef.value.toggleRowSelection(row, undefined)
  }

  // 查询检测项录入结果
  async function getStepCheckPointResult(val) {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();
    if (selections.length !== 1) {
      inputCheckResultObj.checkItemResultList = [];
      return;
    }

    const childContainerSelections = inputCheckResultDialogChildContainerRef.value.getSelectionRows();
    let childContainerList = [];
    for (const i of childContainerSelections) {
      childContainerList.push({
        childcontainerid: i.containerid,
        childcontainername: i.containername,
        containerid: i.parentcontainerid
      });
    }

    const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = selections[0];
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getStepCheckPointResult`,
      data: {
        type: 'getStepCheckPointResult',
        childContainer: childContainerList,//勾选的子批次
        stepCheckPointId: stepcheckpointid,//检查项id
        containerId: containerid,//批次id
        containerStepWorkReportID: ''//报工id
      }
    });
    const reg = /^[+-]?\d+(\.\d+)?$/;//可选正负号开头，其余是合法的数字（含小数）
    for (const i of data.value) {
      // 使用replace方法替换匹配到的内容为空字符串
      const replaceReg = /^(&nbsp;)+|(&nbsp;)+$/g;
      let { basevalue, ceilfloat, floorfloat, workcheckpointresultnote } = i;
      workcheckpointresultnote = workcheckpointresultnote ? workcheckpointresultnote.replace(replaceReg, '') : '';//移除工人录入实测值首尾的空格
      if (reg.test(basevalue) && reg.test(ceilfloat) && reg.test(floorfloat)) {
        let maxValue = parseFloat(basevalue) + parseFloat(ceilfloat);
        let minValue = parseFloat(basevalue) + parseFloat(floorfloat);
        if (reg.test(workcheckpointresultnote)) {
          let inputValue = parseFloat(workcheckpointresultnote);
          if (inputValue < minValue || inputValue > maxValue) {
            i.workerstatus = true;
          }
        }
      }
    }
    inputCheckResultObj.checkItemResultList = data.value;
    inputCheckResultDialogCheckResultTableRef.value.toggleAllSelection();//检测结果表格默认全选
  }

  // 获取检测项内容
  function getCheckItemValue() {
    const iframe = document.getElementById('inputCheckPointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    const innerHTML = elementInIframe.contentDocument.body.innerHTML.trim();
    return innerHTML ? innerHTML.replace(/img/g, "IMG") : '';
  }

  // 清空检测项内容
  function clearCheckItemValue() {
    const iframe = document.getElementById('inputCheckPointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    elementInIframe.contentDocument.body.innerHTML = "";
  }

  function validate() {
    const { containertype } = inputCheckResultObj.containerList[0];
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
    const childContainerList = inputCheckResultDialogChildContainerRef.value.getSelectionRows();//勾选的子批次
    const content = getCheckItemValue();//录入的检测项
    if (selections.length === 0) {
      ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
      return false;
    }
    if (containertype === 3 && childContainerList.length === 0) {
      ElMessage({ type: 'error', message: `请勾选子批次`, grouping: true });
      return false;
    }
    if (!content) {
      ElMessage({ type: 'error', message: `请在【填写区域】内先录入实测值结果`, grouping: true });
      return false;
    }
    return true;
  }

  function isOverTolerance() {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
    let content = getCheckItemValue();//录入的检测项
    const replaceReg = /^(&nbsp;)+|(&nbsp;)+$/g;
    content = content ? content.replace(replaceReg, '') : '';
    const reg = /^[+-]?\d+(\.\d+)?$/;//可选正负号开头，其余是合法的数字（含小数）
    let overTolerance = false;
    for (const i of selections) {
      let { basevalue, ceilfloat, floorfloat } = i;
      if (reg.test(basevalue) && reg.test(ceilfloat) && reg.test(floorfloat) && reg.test(content)) {
        let maxValue = parseFloat(basevalue) + parseFloat(ceilfloat);
        let minValue = parseFloat(basevalue) + parseFloat(floorfloat);
        let inputValue = parseFloat(content);
        if (inputValue < minValue || inputValue > maxValue) {
          overTolerance = true;
          break;
        }
      }
    }
    return overTolerance
  }

  // 【增加】按钮点击
  async function handleCheckPointAddClick() {
    if (validate()) {
      if (isOverTolerance()) {
        ElMessageBox.confirm(`所录入的检测项已超差，确认继续保存?`, '确认', { type: 'error' }).then(async () => {
          await saveCheckResult({ opertype: 'add', stepcheckpointid: '' });
        }).catch(() => {
          ElMessage({ type: 'info', message: '已取消' });
        });
      } else {
        await saveCheckResult({ opertype: 'add', stepcheckpointid: '' });
      }
    }
  }

  // 保存数据
  async function saveCheckResult({ opertype, stepcheckpointid }) {
    const { containertype, containerid, workflowstepid } = inputCheckResultObj.containerList[0];
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=saveCheckResultByWorker`,
      data: {
        type: 'saveCheckResultByWorker',
        content: getCheckItemValue(),//录入的检测项内容
        opertype,//操作类型：add | update
        employeename: currentUserInfo.employeename,
        containerid,//批次id
        containertype,//批次类型
        stepcheckpointid,//检测项id
        childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows(),//勾选的子批次
        stepCheckPointList: inputCheckResultDialogCheckItemTableRef.value.getSelectionRows(),//检测项
        checkPointResultList: inputCheckResultDialogCheckResultTableRef.value.getSelectionRows()//检测项结果
      }
    });
    if (data.value) {
      ElMessage({ type: 'success', message: `保存成功`, grouping: true });
      clearCheckItemValue();
      if (containertype !== 3) {
        await getCheckItemList({ containerid, workflowstepid, stepinfoid: '' })
      } else {
        await getStepCheckPointResult();
      }
    }
  }

  // 【保存】按钮点击
  async function handleUpdateCheckPointValueClick() {
    if (!validate()) { return; }
    const checkResultList = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();//勾选的检测结果
    if (checkResultList.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选已录入结果`, grouping: true });
    }
    if (isOverTolerance()) {
      ElMessageBox.confirm(`所录入的检测项已超差，确认继续保存?`, '确认', { type: 'error' }).then(async () => {
        await saveCheckResult({ opertype: 'update', stepcheckpointid: checkResultList[0].stepcheckpointid });
      }).catch(() => {
        ElMessage({ type: 'info', message: '已取消' });
      });
    } else {
      await saveCheckResult({ opertype: 'update', stepcheckpointid: checkResultList[0].stepcheckpointid });
    }
  }

  // 【删除】检测项
  function deleteCheckPointResult() {
    const selections = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选已录入结果`, grouping: true });
    }
    ElMessageBox.confirm(`你确认要删除吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=deleteCheckPointResult`,
        data: {
          type: 'deleteCheckPointResult',
          deleType: '2',//删除工人实测值
          checkPointResult: selections//勾选的检测项表格数据
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `删除成功`, grouping: true });
        const { containertype } = inputCheckResultObj.containerList[0];
        if (containertype !== 3) {
          const selectCheckItem = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
          const { containerid, workflowstepid } = selectCheckItem[0];
          await getCheckItemList({ containerid, workflowstepid, stepinfoid: '' })
        } else {
          await getStepCheckPointResult();
        }
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  // 推送三坐标
  async function sendToThreeCoordinateRecord() {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
    }

    ElMessageBox.confirm(`你确认要推送三坐标吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=sendToThreeCoordinateRecord`,
        data: {
          type: 'sendToThreeCoordinateRecord',
          checkPoint: selections,//勾选的检测项
          employeename: currentUserInfo.employeename,
          mainParam: inputCheckResultObj.containerList[0]//批次
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `推送成功`, grouping: true });
      } else {
        ElMessage({ type: 'error', message: `${msg}`, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  // 检测项导出
  async function exportCheckPointResult() {
    if (inputCheckResultObj.checkitemList.length === 0) {
      return ElMessage({ type: 'error', message: `批次没有检测项，不能导出`, grouping: true });
    }
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=exportCheckPointFileByWorker`,
      data: {
        type: 'exportCheckPointFileByWorker',
        container: inputCheckResultObj.containerList,
        employeename: currentUserInfo.employeename,
        childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows()//子批次
      }
    });
    if (data.value.filename) {
      ElMessage({ type: 'success', message: `导出成功`, grouping: true });
      const { filename, url } = data.value;
      fileDownload(filename, url);//下载文件
    }
  }

  function fileDownload(filename, url) {
    //通过创建a标签实现
    var link = document.createElement("a");
    link.href = url;
    //对下载的文件命名
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 检测项导入
  async function importCheckPointResult() {
    const fileCount = inputCheckResultObj.checkResultImportfileList.length;
    if (fileCount === 0) {
      return ElMessage({ type: 'error', message: `请先选择要导入的文件`, grouping: true });
    }
    if (fileCount >= 2) {
      return ElMessage({ type: 'error', message: `每次只能上传一个文件，请移除多余的文件`, grouping: true });
    }
    if (inputCheckResultObj.checkitemList.length === 0) {
      return ElMessage({ type: 'error', message: `批次没有检测项，不能导入`, grouping: true });
    }
    inputCheckResultObj.action = `../../../Ashx/InputCheckPointResultVue3PageHandler.ashx?actions=importWorkerCheckPointItem&employeename=${currentUserInfo.employeename}`;
    importCheckResultUploadRef.value.submit();
  }

  // 检测项导入成功事件
  async function handleCheckResultImportSuccess(res) {
    const { ReturnData: data, Message } = res;
    inputCheckResultObj.fileUploadList = [];
    importCheckResultUploadRef.value.clearFiles();//清空已上传的文件列表
    if (data) {
      await getStepCheckPointResult();
      ElMessage({ type: 'success', message: `导入成功`, grouping: true });
    } else {
      ElMessage({ type: 'error', message: `${Message}`, grouping: true });
    }
  }

  // 文件上传
  function uploadFileSubmit() {
    const fileCount = inputCheckResultObj.fileUploadList.length;
    if (fileCount === 0) {
      return ElMessage({ type: 'error', message: `请先选择要导入的文件`, grouping: true });
    }
    if (fileCount >= 2) {
      return ElMessage({ type: 'error', message: `每次只能上传一个文件，请移除多余的文件`, grouping: true });
    }
    const selections = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请选择实测值结果`, grouping: true });
    }
    inputCheckResultObj.fileUploadParams.checkPointResult = JSON.stringify(selections);
    fileUploadRef.value.submit();
  }

  // 文件上传成功
  function handleFileUploadSuccess(res) {
    inputCheckResultObj.fileUploadParams.checkPointResult = [];
    const { ReturnData: data, Message } = res;
    if (data) {
      ElMessage({ type: 'success', message: `文件上传成功`, grouping: true });
      fileUploadRef.value.clearFiles();//清空已上传的文件列表
      inputCheckResultObj.fileUploadList = [];
    } else {
      ElMessage({ type: 'error', message: `${Message}`, grouping: true });
    }
  }

  return {
    inputCheckResultObj,
    initInputCheckResultDialogData,
    inputCheckResultDialogCheckItemTableRef,//检测项表格ref
    inputCheckResultDialogChildContainerRef,//子序号批次表格ref
    inputCheckResultDialogCheckResultTableRef,//检测项结果表格ref
    importCheckResultUploadRef,//检查项导入ref
    getStepCheckPointResult,//查询检测项录入结果
    handleCheckPointAddClick,//【增加】按钮点击
    handleUpdateCheckPointValueClick,//【保存】按钮点击
    deleteCheckPointResult,//删除检测项
    exportCheckPointResult,//导出检测项
    importCheckPointResult,//导入检测项
    handleCheckResultImportSuccess,//检测项导入成功事件
    checkItemRowClick,//检测项row点击事件
    sendToThreeCoordinateRecord,//推送三坐标
    fileUploadRef,//文件上传ref
    handleFileUploadSuccess,//文件上传成功事件
    uploadFileSubmit,//文件上传提交
  };
}